package com.doubao.chat.service;

import com.doubao.chat.entity.ChatMessage;
import com.doubao.chat.mapper.ChatMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 聊天归档服务
 * 负责将聊天会话保存为文本文件
 */
@Service
@Slf4j
public class ChatArchiveService {

    private final ChatMessageMapper chatMessageMapper;
    // private final FileService fileService;

    @Autowired
    public ChatArchiveService(ChatMessageMapper chatMessageMapper
                             /* FileService fileService */) {
        this.chatMessageMapper = chatMessageMapper;
        // this.fileService = fileService;
    }

    /**
     * 将会话保存为txt文档
     */
    @Async
    public void archiveSessionToTxt(Long sessionId, Long userId) {
        if (sessionId == null || userId == null) {
            log.warn("会话ID或用户ID为空，无法归档");
            return;
        }

        try {
            // 获取会话的所有消息
            List<ChatMessage> messages = chatMessageMapper.selectSessionAllMessages(sessionId);

            if (messages == null || messages.isEmpty()) {
                log.warn("会话{}没有消息，跳过归档", sessionId);
                return;
            }

            log.info("会话{}有{}条消息，暂不归档（文件服务功能尚未实现）", sessionId, messages.size());
            
            /*
            // 构建文本内容
            StringBuilder content = new StringBuilder();
            content.append("会话ID: ").append(sessionId).append("\n");
            content.append("归档时间: ").append(LocalDateTime.now()).append("\n\n");

            for (ChatMessage message : messages) {
                String role = "user".equals(message.getRole()) ? "用户" : "AI";
                content.append(role).append(" (")
                        .append(message.getCreatedAt())
                        .append("):\n");
                content.append(message.getContent()).append("\n\n");
            }

            // 生成聊天ID (用于文件服务)
            String chatId = "session_" + sessionId;

            // 生成消息ID
            String messageId = "archive_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));

            // 保存文件
            FileInfoResponse fileInfo = fileService.saveChatMessage(
                    userId, chatId, content.toString(), messageId);

            log.info("会话{}归档成功: {}", sessionId, fileInfo.getObjectName());
            */
        } catch (Exception e) {
            log.error("会话{}归档失败", sessionId, e);
        }
    }
}